//
//  QuickEditCategoryView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 08.05.25.
//

import SwiftUI

struct QuickEditCategoryView: View {
    
    @Environment(\.presentationMode) var presentationMode;
    
    @StateObject var viewModel = QuickEditCategoryViewModel()
    @State var selectedCategory: AccountingCategory?
    @State var selectedBookId: String? = nil
    @State var categoryType: CategoryType = .expense
    var onCategorySelect: ((AccountingCategory)->Void)
    
    var body: some View {
        VStack {
            ZStack (alignment: .center) {
                CategoryTypeView(categoryType: $categoryType)
                    .padding(EdgeInsets(top: 16, leading: 0, bottom: 6, trailing: 0))
                
                HStack (alignment: .center) {
                    KoiBackButton()
                    Spacer()
                }
                
                HStack {
                    Spacer()
                    Button(action:{
                        if let selectedSubCategory = viewModel.selectedSubCategory {
                            onCategorySelect(selectedSubCategory)
                        } else if let selectedCategory = viewModel.selectedCategory {
                            onCategorySelect(selectedCategory)
                        }
                        presentationMode.wrappedValue.dismiss()
                    }) {
                        Text("确定")
                            .font(.system(size: 15))
                            .bold()
                            .foregroundColor(Color.koiColorPrimary)
                            .padding(.horizontal, 14)
                    }
                }
            }
            TabView(selection: $categoryType) {
                CategoryGridView(
                    categoryList: $viewModel.expenseList,
                    subCategoryList: $viewModel.subCategoryList,
                    selectedCategory: $viewModel.selectedCategory,
                    selectedSubCategory: $viewModel.selectedSubCategory,
                    expand: $viewModel.isExpand,
                    onCategoryClick: { category in
                        viewModel.loadSubCategoryList(category: category, selectedBookId: selectedBookId)
                    }
                ).tag(CategoryType.expense)
                CategoryGridView(
                    categoryList: $viewModel.incomeList,
                    subCategoryList: $viewModel.subCategoryList,
                    selectedCategory: $viewModel.selectedCategory,
                    selectedSubCategory: $viewModel.selectedSubCategory,
                    expand: $viewModel.isExpand,
                    onCategoryClick: { category in
                        viewModel.loadSubCategoryList(category: category, selectedBookId: selectedBookId)
                    }
                ).tag(CategoryType.income)
            }
            .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
        }
        .navigationBarBackButtonHidden()
//        .onChange(of: viewModel.selectedCategory) { value in
//            viewModel.loadSubCategoryList(category: value)
//        }
        .onAppear {
            viewModel.loadCategorys(selectedCategory: selectedCategory, selectedBookId: selectedBookId)
        }
    }
}

struct CategoryGridView : View {
    
    var columns = [
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top)
    ]
    
    @Binding var categoryList:Array<AccountingCategory>
    @Binding var subCategoryList:Array<AccountingCategory>
    @Binding var selectedCategory: AccountingCategory?
    @Binding var selectedSubCategory: AccountingCategory?
    @Binding var expand: Bool
    @State var gridItemHeight = Float(0)
    @State var gridItemWidth = CGFloat(0)
    @State var placeHeight = Float(0)
    
    var onCategoryClick:(AccountingCategory?)->Void
    
    init(categoryList: Binding<Array<AccountingCategory>>,
         subCategoryList: Binding<Array<AccountingCategory>>,
         selectedCategory: Binding<AccountingCategory?>,
         selectedSubCategory: Binding<AccountingCategory?>,
         expand: Binding<Bool>,
         onCategoryClick: @escaping (AccountingCategory?) -> Void
    ) {
        self._categoryList = categoryList
        self._subCategoryList = subCategoryList
        self._selectedCategory = selectedCategory
        self._selectedSubCategory = selectedSubCategory
        self._expand = expand
        self.onCategoryClick = onCategoryClick
    }
    
    var body: some View {
        GeometryReader { proxy in
            ScrollView {
                LazyVGrid(columns: columns) {
                    ForEach(0..<categoryList.count, id: \.self) { index in
                        let category = categoryList[index]
                        VStack {
                            Button(action: {
                                if expand {
                                    if selectedCategory?.cid == category.cid {
                                        withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
                                            expand = false
                                            selectedSubCategory = nil
                                            subCategoryList = Array()
                                        }
                                    } else {
                                        selectedSubCategory = nil
                                        selectedCategory = category
                                        onCategoryClick(category)
                                    }
                                } else {
                                    selectedSubCategory = nil
                                    selectedCategory = category
                                    onCategoryClick(category)
                                }
                            }) {
                                CategoryGridItemView(category: category, isSelected: category.cid == selectedCategory?.cid)
                                    .overlay(
                                        GeometryReader { p in
                                            Color.clear.task {
                                                gridItemHeight = Float(p.size.height)
                                                gridItemWidth =  p.size.width
                                                let colCount = Float(columns.count)
                                                let subCount = Float(subCategoryList.count)
                                                let subRow = ceilf(subCount / colCount)
                                                placeHeight = subRow * gridItemHeight + subRow*10 + 20
                                                print("CategoryGridItemView  overlay \(expand)")
                                            }})
                            }
                            if expand && category.cid == selectedCategory?.cid && !subCategoryList.isEmpty {
                                Color.clear.frame(height: CGFloat(placeHeight))
                                    .overlay {
                                        Group {
                                            GeometryReader { subProxy in
                                                let overlayOffset = subProxy.frame(in: .named("rootView")).minX
                                                let offset = overlayOffset + gridItemWidth / 2
                                                LazyVGrid(columns: columns, alignment: .center) {
                                                    ForEach(subCategoryList) { item in
                                                        Button(action: {
                                                            selectedSubCategory = item
                                                        }) {
                                                            CategoryGridItemView(category: item, isSelected: item.cid == selectedSubCategory?.cid)
                                                        }
                                                    }
                                                }
                                                .frame(width: proxy.size.width-20)
                                                .padding(.top, 20)
                                                .padding(.bottom, 10)
                                                .background(KoiArrowBackground(offset:offset).fill(Color.koiColorDivider))
                                                .cornerRadius(16)
                                                .padding(.horizontal, 10)
                                                .offset(x: -overlayOffset)
                                            }
                                        }
                                    }
                            }
                        }
                    }
                }
                .onChange(of: subCategoryList) { value in
                    if subCategoryList.isEmpty {
                        withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
                            print("onChange  subCategoryList expand to false")
                            expand = false
                        }
                        return
                    }
                    let colCount = Float(columns.count)
                    let subCount = Float(subCategoryList.count)
                    let subRow = ceilf(subCount / colCount)
                    placeHeight = subRow * gridItemHeight + subRow*10 + 20
                    withAnimation(.spring(response: 0.4, dampingFraction: 0.7)) {
                        expand = true
                    }
                    print("onChange  subCategoryList placeHeight \(placeHeight)")
                }
            }
        }
        .coordinateSpace(name:"rootView")
        .onAppear {
            print("selectedCategory \(selectedCategory?.name)")
            print("selectedSubCategory \(selectedSubCategory?.name)")
        }
    }
}

#Preview {
    QuickEditCategoryView(selectedCategory: nil, categoryType: .expense, onCategorySelect: { category in })
}
